//
//  MYXSettingViewController.m
//  meiyinxiang
//
//  Created by 陈李飞 on 2017/10/28.
//  Copyright © 2017年 hbjApple. All rights reserved.
//设置

#import "MYXSettingViewController.h"
#import "MYXChangePhoneViewController.h"
#import "MYXForgotPasswordViewController.h"
#import "AboutMeController.h"
#import "MYXsignatureViewController.h"

#import "LxxPlaySound.h"
#import "JXTActionSheet.h"
#import "MYXSettingCell.h"
#import "MYY_Me_Macro.h"
#import "MYXAuthenticationTopView.h"

#import "MYXMemberMdel.h"
#import "userinfoModel.h"
#import "MYXchatViewController.h"
static NSString *const MYXAuthenticationTopViewIdentifier = @"MYXAuthenticationTopView";

@interface MYXSettingViewController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate,JXTActionSheetDelegate>
@property (nonatomic, strong)UITableView * m_tabView ;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong)NSMutableArray *titleArray;//文字数组
@property (nonatomic, strong)MYXAuthenticationTopView *MYXAuthenticationTopV;
@property(nonatomic,strong)MYXHttpManager *MYXHttpManag;
//@property(nonatomic,strong)userinfoModel *userinfoMode;
@end

@implementation MYXSettingViewController
-(NSMutableArray *)dataArr
{
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    
    return _dataArr;
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.MYXHttpManag =[[MYXHttpManager alloc]init];
//    self.userinfoMode =[[userinfoModel alloc]init];
//    self.userinfoMode = [MYXMemberMdel sharedInstance].userinfo;
    [self createUI];
}


#pragma mark - UI

- (void)createUI
{
    [self.view addSubview:self.m_tabView];
}
#pragma mark -设置

-(UITableView *)m_tabView
{
    if (!_m_tabView)
    {
        _m_tabView = [[UITableView alloc]initWithFrame:CGRectMake(0,0, WIDTH, HEIGHT-SafeAreaTopHeight) style:UITableViewStyleGrouped];
        _m_tabView.backgroundColor =  [UIColor colorWithRed:0.95f green:0.96f blue:0.96f alpha:1.00f];
        _m_tabView.separatorStyle=UITableViewCellSeparatorStyleNone;
        _m_tabView.showsVerticalScrollIndicator = NO;
        _m_tabView.dataSource = self;
        _m_tabView.delegate = self;
    }
    
    return _m_tabView;
}


#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    switch (section) {
        case 0:
            return 2;
        case 1:
            return 1;
        case 2:
            return 2;
        default:
            return 3;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MYXSettingCell *MYXSettingCe = [MYXSettingCell cellWithTableView:tableView];
    MYXSettingCe.backgroundColor =[UIColor whiteColor];
    if (indexPath.section == 0) {
        NSString *titiStr;
        if (indexPath.row==0) {
            titiStr = @"查看手机通讯录";
            [MYXSettingCe setSettingName:titiStr detailText:@"" infoText:@"" indicator:YES switchButton:NO topHeight:0 switchChanged:nil];
        }else{
            titiStr = @"设置/修改支付密码";
            if ([MYXMemberMdel sharedInstance].userinfo.paypassword.length>0) {
                 [MYXSettingCe setSettingName:titiStr detailText:@"" infoText:@"已绑定" indicator:YES switchButton:NO topHeight:0 switchChanged:nil];
            }else{
                 [MYXSettingCe setSettingName:titiStr detailText:@"" infoText:@"未绑定" indicator:YES switchButton:NO topHeight:0 switchChanged:nil];
            }
           
        }
        
    }else if(indexPath.section == 1){
        if (indexPath.row==0) {
          
            if ([[MYXMemberMdel sharedInstance].userinfo.is_match isEqualToString:@"0"]) {
                [MYXSettingCe changeSwitchState:NO];
            }else if ([[MYXMemberMdel sharedInstance].userinfo.is_match isEqualToString:@"1"]){
                [MYXSettingCe changeSwitchState:YES];
            }
            
            [MYXSettingCe setSettingName:@"推荐手机联系人" detailText:@"" infoText:@"" indicator:NO switchButton:YES topHeight:0 switchChanged:^(BOOL on) {
                if (on) {
                    NSLog(@"开");
                    [self initismatchRequest:@"1"];
                    
                }else{
                    [self initismatchRequest:@"0"];
                }

                
            }];
        }else if (indexPath.row==1){
            [MYXSettingCe setSettingName:@"聊过的人" detailText:@"" infoText:@"" indicator:YES switchButton:NO topHeight:0 switchChanged:nil];
        }else if (indexPath.row==2){
            [MYXSettingCe setSettingName:@"黑名单" detailText:@"" infoText:@"" indicator:YES switchButton:NO topHeight:0 switchChanged:nil];
        }
    }else if (indexPath.section == 2) {
        if (indexPath.row == 0) {
           // [MYXSettingCe setSettingName:@"声音" detailText:@"" infoText:@"" indicator:NO switchButton:YES topHeight:0 switchChanged:nil];
            [MYXSettingCe setSettingName:@"声音" detailText:@"" infoText:@"" indicator:NO switchButton:YES topHeight:0 switchChanged:^(BOOL on) {
                
                if (on) {
                    LxxPlaySound *sound =        [[LxxPlaySound alloc] initForPlayingSystemSoundEffectWith:@"new-mail.caf" ofType:@"MailReceived"];
                    [sound play];
                }
            }];
        }else if (indexPath.row==1){
          //  [MYXSettingCe setSettingName:@"震动" detailText:@"" infoText:@"" indicator:NO switchButton:YES topHeight:0 switchChanged:nil];
            [MYXSettingCe setSettingName:@"震动" detailText:@"" infoText:@"" indicator:NO switchButton:YES topHeight:0 switchChanged:^(BOOL on) {
                if (on) {
                    LxxPlaySound *sound = [[LxxPlaySound alloc] initForPlayingVibrate];
                    [sound play];
                }
            }];
            
        }
    }
    else if (indexPath.section == 3) {
        if (indexPath.row==0) {
             [MYXSettingCe setSettingName:@"关于媒印象" detailText:@"" infoText:@"" indicator:YES switchButton:NO topHeight:0 switchChanged:nil];
        }else if (indexPath.row==1){
             [MYXSettingCe setSettingName:@"问题反馈" detailText:@"" infoText:@"" indicator:YES switchButton:NO topHeight:0 switchChanged:nil];
            
        }else if (indexPath.row==2){
             [MYXSettingCe setSettingName:@"清除缓存" detailText:@"" infoText:[NSString stringWithFormat:@"%.1fMB",[self cacheSize]] indicator:YES switchButton:NO topHeight:0 switchChanged:nil];
        }
       
    }
    return MYXSettingCe;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{
    
    return 44;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *fooerView =[[UIView alloc]init];
    if (section==3) {
        fooerView.frame                         = CGRectMake(0, 0, WIDTH, 70);
        fooerView.backgroundColor =[UIColor colorWithRed:0.96f green:0.96f blue:0.96f alpha:1.00f];
        
        UIButton *  _button = [[UIButton alloc] initWithFrame:CGRectMake(10, (fooerView.frame.size.height-(tab_h-10))/2, fooerView.frame.size.width-20, tab_h-10)];
        [_button setBackgroundColor:MYYheadColor];
        _button.clipsToBounds = YES;
        _button.layer.cornerRadius = 20;
        [_button setTitle:@"退出登录" forState:UIControlStateNormal];
        [_button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_button addTarget:self action:@selector(entered) forControlEvents:UIControlEventTouchUpInside];
        _button.titleLabel.font =[UIFont systemFontOfSize:14];
        [fooerView addSubview:_button];
    }else{
        fooerView.frame                         = CGRectMake(0, 0, WIDTH, 0.1);
    }
   
    return fooerView;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section==3) {
         return 70;
    }
    return 0.1;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *HeaderView =[[UIView alloc]init];

        HeaderView.frame                         = CGRectMake(0, 0, WIDTH, 34);
        HeaderView.backgroundColor =[UIColor colorWithRed:0.96f green:0.96f blue:0.96f alpha:1.00f];
        self.MYXAuthenticationTopV                                =[[NSBundle mainBundle]loadNibNamed:MYXAuthenticationTopViewIdentifier owner:self options:nil][0];
        self.MYXAuthenticationTopV.frame = CGRectMake(0, 0, HeaderView.frame.size.width,HeaderView.frame.size.height);
        [HeaderView addSubview:self.MYXAuthenticationTopV];
     self.MYXAuthenticationTopV.Label.textColor =  MYYColorFromRGB(0xa6a6a6);
    self.MYXAuthenticationTopV.Label.font = MYYFont(15.0f);
        if (section==0) {
            self.MYXAuthenticationTopV.Label.text = @"账户与安全";
        }else if (section==1){
            self.MYXAuthenticationTopV.Label.text = @"通用";
        }else if (section==2){
            self.MYXAuthenticationTopV.Label.text = @"通知";
        }else if (section==3){
            self.MYXAuthenticationTopV.Label.text = @"关于";
        }
    return HeaderView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 34;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        if (indexPath.row==0) {
            MYXChangePhoneViewController *MYXChangePhoneVC =[[MYXChangePhoneViewController alloc]init];
            MYXChangePhoneVC.navigationItem.title = @"修改绑定手机";
            MYXChangePhoneVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:MYXChangePhoneVC animated:YES];
        }else if (indexPath.row==1){
            MYXForgotPasswordViewController *MYXForgotPasswordViewControl = [[MYXForgotPasswordViewController alloc] init];
            MYXForgotPasswordViewControl.selectBlock=^(NSString *payPassword){
               [MYXMemberMdel sharedInstance].userinfo.paypassword =payPassword;
                [[MYXMemberMdel sharedInstance] save];
                [self.m_tabView reloadData];
            };
            MYXForgotPasswordViewControl.navigationItem.title =@"设置支付密码";
            MYXForgotPasswordViewControl.type=2;
            [self.navigationController pushViewController:MYXForgotPasswordViewControl animated:YES];
        }
    }else if (indexPath.section==1){
         if (indexPath.row==2){
             /*
             MYXchatViewController *MYXchatVC =[[MYXchatViewController alloc]init];
             MYXchatVC.navigationItem.title =@"黑名单";
             [self.navigationController pushViewController:MYXchatVC animated:YES];
              */
         }
        
    }else if (indexPath.section == 3){
        if (indexPath.row == 0) {//关于媒印象
            AboutMeController *aboutMe = [AboutMeController loadNibWithMeVC];
            [self.navigationController pushViewController:aboutMe animated:YES];
        }else if (indexPath.row == 1){//问题反馈
            MYXsignatureViewController *MYXsignatureVC =[[MYXsignatureViewController alloc]init];
            MYXsignatureVC.placehoderString= @"请填写相应您的反馈意见，我们将为您提供更好的服务";
            MYXsignatureVC.companyIntrLabel.hidden = NO;

            WS(weakSelf);
            MYXsignatureVC.signatureBlock =^(NSString * signature){//提交问题反馈
            
                [[MYXHttpManager shared] postQuestionWithContent:signature withResult:^(BOOL sucess, NSString *msg) {
                    if (sucess) {
                        [weakSelf showTopMessage:@"已为您提交反馈信息，我们将尽快帮您解决问题"];
                    }
                }];
            };
            MYXsignatureVC.navigationItem.title= @"问题反馈";
            [self.navigationController pushViewController:MYXsignatureVC animated:YES];
        }else if (indexPath.row == 2){//清楚缓存
            JXTActionSheet *actionSheet = [[JXTActionSheet alloc] initWithTitle:@"确定要清楚缓存数据吗?为节约流量建议使用wifi接入。" buttonTitles:[[NSArray alloc] initWithObjects:@"清楚数据缓存", nil] redButtonIndex:0 delegate:self];
            actionSheet.tag = 10002;
            [actionSheet show];
        }
    }
   
}

- (void)changeSubstituteState:(BOOL)canSubstitute
{
    NSIndexPath *indexpath = [NSIndexPath indexPathForRow:1 inSection:1];
    MYXSettingCell *cell = [self.m_tabView cellForRowAtIndexPath:indexpath];
    if (cell && [cell isKindOfClass:[MYXSettingCell class]]) {
        [cell changeSwitchState:canSubstitute];
    }
}


-(void)entered
{
    GRLog(@"退出登录");
    // 退出登陆
    JXTActionSheet *actionSheet = [[JXTActionSheet alloc] initWithTitle:@"确定要退出登录吗?" buttonTitles:[[NSArray alloc] initWithObjects:@"确定", nil] redButtonIndex:0 delegate:self];
    actionSheet.tag = 10001;
    [actionSheet show];
}

- (void)actionSheet:(JXTActionSheet *)actionSheet didClickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (actionSheet.tag == 10001) {
        if (buttonIndex == 0) {
            MYY_User *user = [MYY_User readUserFromFile];
            user.isLogin = NO;
            user.token = nil;
            [user save];
            MYXMemberMdel *MYXMemberM = [MYXMemberMdel  sharedInstance];
            [MYXMemberM save];
           // [MYXMemberM]
            [self.navigationController popViewControllerAnimated:YES];
            //            PB_LoginController *login = [[PB_LoginController alloc] init];
            //            JXTNavigationController *nvc = [[JXTNavigationController alloc] initWithRootViewController:login];
            //            if ( [[NSFileManager defaultManager] removeItemAtPath:USER_DATA_FILE error:nil]) {
            //
            //                [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"isLogin"];
            //                [ [NSUserDefaults standardUserDefaults] synchronize];
            //                [self presentViewController:nvc animated:YES completion:nil];
            //                
            //                
            //            }
        }
    }else if (actionSheet.tag == 10002){
        if (buttonIndex == 0) {//FIXME:清楚数据缓存
            
            
        }
    }
}

- (CGFloat)cacheSize
{
    float cacheSize;
    MYY_User *user = [MYY_User readUserFromFile];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *filePath = [[[paths objectAtIndex:0] stringByAppendingString:@"/Caches/"] stringByAppendingString:user.accid];
    
    NSString *audioPath = [filePath stringByAppendingString:@"/Audios"];
    NSString *imagePath = [filePath stringByAppendingString:@"/upload"];
    
    cacheSize = [self folderSizeAtPath:audioPath]+[self folderSizeAtPath:imagePath];
    return cacheSize;
}



#pragma mark - private
//遍历文件夹获得文件夹大小，返回多少M
- (float ) folderSizeAtPath:(NSString*) folderPath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]) return 0;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString* fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize/(1024.0*1024.0);
}

- (long long) fileSizeAtPath:(NSString*) filePath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}

-(void)initismatchRequest:(NSString *)ismatch{
    [self.MYXHttpManag ismatch:ismatch success:^(NSString *dataStr) {
        //更新缓存
        MYXMemberMdel *userModel = [MYXMemberMdel sharedInstance];
        if ([ismatch isEqualToString:@"1"]) {
            [JXTHUDHelper showHUDText:@"关闭成功～" type:@"success" inView:nil];
            userModel.userinfo.is_match = @"0";;
          //  [userModel updateUser];
            
        }else if ([ismatch isEqualToString:@"0"]){
            [JXTHUDHelper showHUDText:@"开启成功～" type:@"success" inView:nil];
            userModel.userinfo.is_match = @"1";
           // [userModel updateUser];
            
        }
       
        
    } failure:^(NSString *errorCode) {
         [JXTHUDHelper showHUDText:errorCode type:@"error" inView:nil];
    } netDown:^{
         [JXTHUDHelper showHUDText:@"网络出错了～" type:@"error" inView:nil];
    }];
  
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
